package com.amtf.datafile2.core.excel;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.amtf.datafile2.DataException;
import com.amtf.datafile2.cfg.excel.ExcelDataFieldDefinition;
import com.amtf.datafile2.cfg.excel.ExcelDataTableDefinition;
import com.amtf.datafile2.cfg.excel.ExcelDataTableDefinitionStore;
import com.amtf.datafile2.core.std.StdDataCatalog;

public class ExcelDataCatalog extends StdDataCatalog<ExcelDataTable, ExcelDataTableDefinition, ExcelDataFieldDefinition> {
	private Workbook workbook = null;

	public ExcelDataCatalog(String name, Workbook workbook) throws DataException {
		super(name);
		this.workbook = workbook;

		int size = workbook.getNumberOfSheets();
		for (int i = 0; i < size; i++) {
			Sheet sheet = workbook.getSheetAt(i);
			if (sheet == null) {
				throw new DataException("Could not get sheet at index " + i);
			}

			ExcelDataTable dt = new ExcelDataTable(sheet.getSheetName(), sheet, ExcelDataTableDefinitionStore.DEFAULT_EXCEL_DEFINITION.clone());
			setDataTable(sheet.getSheetName(), dt);
		}
	}

	public Workbook getWorkbook() {
		return workbook;
	}

	public ExcelDataTable createDataTable(String name, ExcelDataTableDefinition definition) throws DataException {
		Sheet sheet = workbook.createSheet(name);
		ExcelDataTable workSheet = this.getDataTable(name);
		if (workSheet == null) {
			workSheet = new ExcelDataTable(name, sheet, definition);
			setDataTable(name, workSheet);
		}

		return workSheet;
	}

	@Override
	public ExcelDataTable dropDataTable(String name) throws DataException {
		ExcelDataTable dt = super.getDataTable(name);
		if (dt != null) {
			dt.close();
			int index = workbook.getSheetIndex(name);
			if (index > 0) {
				workbook.removeSheetAt(index);

				return super.dropDataTable(name);
			}
		}
		return null;
	}
}
